import queue
import logging
import threading
import time
import socket
import json
from datetime import datetime

class UdpOut:
    def __init__(self):
        self.run = False
        self.__log_init()


    def __log_init(self):
        self.logger = logging.getLogger("UdpOut")


    def open(self, host, port):
        self.logger.trace('open.enter')
        
        self.addr = (host, port)
        self.skt = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        
        self.logger.trace('open.done')
        return True


    def close(self):
        self.logger.trace('close.enter')
        
        self.skt.close()

        self.logger.trace('close.done')


    def thread(self):
        self.logger.trace('thread.enter')

        while self.run:
            try:
                data = self.inqueue1.get(timeout=0.5)
                if not data:
                    continue
            except queue.Empty:
                continue
            except Exception as e:
                self.logger.error(f"Error in thread: {e}")
                continue
            
            data_to_send = json.dumps(data).encode("utf-8")
            try:
                self.skt.sendto(data_to_send, self.addr)
                self.logger.verbose(f"Sent data to {self.addr}: {data_to_send.decode('utf-8')}")
            except Exception as e:
                self.logger.error(f"Error: {e}")

        self.logger.trace('thread.done')


    def start(self):
        self.logger.trace('start.enter')

        self.run = True
        self.handle = threading.Thread(target=self.thread)
        self.handle.start()

        self.logger.trace('start.done')
        return True


    def stop(self):
        self.logger.trace('stop.enter')
        self.run = False
        self.handle.join()
        self.logger.trace('stop.done')


    def input_queue_set(self, input_queue_list):
        # 设置输入队列，接受的是一个队列列表
        self.logger.trace('input_queue_set.enter')

        if self.run:
            self.logger.error("udpout is opened, please close the udpout first!")
            return False
        
        if not isinstance(input_queue_list, list):
            input_queue_list = [input_queue_list]

        for input_queue in input_queue_list:
            if not isinstance(input_queue, queue.Queue):
                self.logger.error("one queue is not a queue!")
                return False

        self.inqueue1 = input_queue_list[0] 

        self.logger.trace('input_queue_set.done')
        return True
